﻿using DotNetty.Transport.Channels.Sockets;
using DotNetty.Transport.Channels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DotNetty.Buffers;
using DotNetty.Codecs;
using MedianSocketService.netty.MedianProtocol;

namespace MedianSocketService.netty.HighPowerProtocol
{
    public class HighPowerInitializer : ChannelInitializer<ISocketChannel>
    {
        public Action<SocketClientInfo> OnConnectedCompletedDelegate;
        public Action<SocketClientInfo, byte[]> OnReceiveCompletedDelegate;
        public Action<SocketClientInfo> OnDisConnectedDelegate;

        protected override void InitChannel(ISocketChannel channel)
        {
            IChannelPipeline pipeline = channel.Pipeline;
            //自定义解码器
            pipeline.AddLast(new HighPowerDecoder());
            //请求消息处理类
            HighPowerHandler highPowerHandler = new HighPowerHandler();
            highPowerHandler.OnConnectedCompletedDelegate = OnConnectedCompleted;
            highPowerHandler.OnDisConnectedDelegate = OnDisConnected;
            highPowerHandler.OnReceiveCompletedDelegate = OnReceiveCompleted;
            pipeline.AddLast(highPowerHandler);
        }

        public void OnConnectedCompleted(SocketClientInfo sci)
        {
            if (OnConnectedCompletedDelegate != null)
            {
                OnConnectedCompletedDelegate(sci);
            }
        }
        private void OnDisConnected(SocketClientInfo sci)
        {
            if (OnDisConnectedDelegate != null)
            {
                OnDisConnectedDelegate(sci);
            }
        }
        public void OnReceiveCompleted(SocketClientInfo sci, byte[] recvData)
        {
            if (OnReceiveCompletedDelegate != null)
            {
                OnReceiveCompletedDelegate(sci, recvData);
            }
        }
    }
}
